import UrlConst from './common/UrlConst';
import C2CTradeHelper from './common/C2CTradeHelper';
import SpotTradeHelper from './common/SpotTradeHelper';
import userConfig from '../config/userConfig'
import GmHelper from './../common/GmHelper';
import DomHelper from './../common/DomHelper';
import OkexWebUtils from './common/OkexWebUtils';
import CacheHelper from './../common/CacheHelper';

const OkexC2CWebUtils = OkexWebUtils.okexC2CWebUtils();
const OkexSpotWebUtils = OkexWebUtils.okexSpotWebUtils();

const notifyLogo = require('../res/okex/img/logo_okex_v2.png');
const notifySound = require('../res/okex/sound/qq-notify.mp3');

//C2C交易配置
const okexC2CConfigCacheKey = 'okex-c2c-setting-key';
const okexC2CDefaultConfig = {
    isEnabled: false,
    icon: notifyLogo,
    sound: notifySound,
    autoBuyPrice: 6.3,
    autoSellPrice: 6.99,
    isAutoSell: false,
    diffPrice: 0.01,
    maxAutoTradeAmt: 10000,
    finishRate: 80,
    jobTimeRange: '00:00 - 23:59',
    autoRefreshInterval: 10 * 60,
    defaultEntrustTime: 3,
    entrustTime: 0.3
};
const okexC2CConfig = (() => {
    const okexC2CCacheConfig = CacheHelper.get(okexC2CConfigCacheKey);
    Object.assign(okexC2CDefaultConfig, okexC2CCacheConfig);
    return okexC2CDefaultConfig;
})();

//币币交易配置
const okexSpotConfigCacheKey = 'okex-spot-setting-key';
const okexOldHtmlCacheKey = 'okex-old-html-key';
const okexSpotDefaultConfig = {
    isEnabled: false,
    icon: notifyLogo,
    sound: notifySound,
    diffPrice: 0.0001,
    autoBuyPercent: 5,
    autoSellPercent: 5,
    jobTimeRange: '00:00 - 23:59',
    autoRefreshInterval: 10 * 60,
};
const okexSpotConfig = (() => {
    const okexSpotCacheConfig = CacheHelper.get(okexSpotConfigCacheKey);
    Object.assign(okexSpotDefaultConfig, okexSpotCacheConfig);
    return okexSpotDefaultConfig;
})();
const tradeType = {
    isC2C: (() => {
        return location.href.toLowerCase().includes('/fiat/c2c');
    })(),
    isSpot: (() => {
        return location.href.toLowerCase().includes('/spot/trade');
    })(),
}

class GmUserJs {
    init() {
        const self = this;
        if (!userConfig.isProductionEnv) {
            GmHelper.init();
        }
        self.initLayui();
    }

    initLayui() {
        const self = this;

        DomHelper.createCss(userConfig.layuiCssPath);

        const layuiBasePath = userConfig.layuiBasePath;
        layui.config({
            dir: `${userConfig.baseUrl}${layuiBasePath}`,
            version: false,
            debug: false,
            base: `${userConfig.baseUrl}${layuiBasePath}`
        }).extend({
            'progressSlider': 'lay/modules/extend/progressSlider'
        });
        layui.use(['util', 'jquery', 'layer', 'form', 'element', 'progressSlider', 'laydate'], () => {
            const util = layui.util;
            const $ = layui.jquery;
            const layer = layui.layer;
            const form = layui.form;
            const element = layui.element;
            const progressSlider = layui.progressSlider;
            const laydate = layui.laydate;

            if (tradeType.isC2C) {
                if (okexC2CConfig.isEnabled) {
                    self.startTrade();
                }
                //固定块
                util.fixbar({
                    bar1: '&#xe631;',
                    bar2: okexC2CConfig.isEnabled ? '&#xe651;' : '&#xe652;',
                    css: {
                        top: 100,
                        right: 10
                    },
                    bgcolor: '#0096df',
                    click: function (type) {
                        const clickEle = this;
                        if (type === "bar1") {
                            //页面层
                            const formHtml = GM_getResourceText('frm-okex-c2c-setting');
                            const settingLayerIndex = layer.open({
                                title: '配置',
                                type: 1,
                                skin: 'layui-layer-rim', //加上边框
                                area: ['800px', '540px'], //宽高
                                content: formHtml
                            });
                            form.render();
                            //默认值
                            //formTest 即 class="layui-form" 所在元素对应的 lay-filter="" 对应的值

                            const frmFitter = 'okex-setting';
                            form.val(frmFitter, okexC2CConfig);
                            //进度条滑动
                            element.progress('finishRate', okexC2CConfig.finishRate + '%');
                            progressSlider.render('finishRate', (percent) => {
                                form.val(frmFitter, {
                                    finishRate: percent
                                });
                            });
                            //工作时间范围
                            laydate.render({
                                elem: '.jobTimeRange',
                                type: 'time',
                                range: true,
                                format: 'HH:mm'
                            });

                            //监听提交
                            form.on('submit(frm-okex-save)', function (data) {
                                Object.assign(okexC2CConfig, data.field);
                                CacheHelper.set(okexC2CConfigCacheKey, okexC2CConfig);
                                layer.close(settingLayerIndex);
                                layer.msg('保存成功');
                                return false;
                            });

                        } else if (type === 'bar2') {
                            const bar2Self = this;
                            $(bar2Self).text('');
                            if (okexC2CConfig.isEnabled) {
                                $(bar2Self).removeClass('layui-icon-pause').addClass('layui-icon-play');
                                self.stopTrade();
                            } else {
                                $(bar2Self).addClass('layui-icon-pause').removeClass('layui-icon-play');
                                self.startTrade();
                            }
                        }
                    }
                });
            } else if (tradeType.isSpot) {
                const okexSpotCacheConfig = CacheHelper.get(okexSpotConfigCacheKey);
                Object.assign(okexSpotConfig, okexSpotCacheConfig);

                if (okexSpotConfig.isEnabled) {
                    self.startTrade();
                }
                //固定块
                util.fixbar({
                    bar1: '&#xe631;',
                    bar2: okexSpotConfig.isEnabled ? '&#xe651;' : '&#xe652;',
                    css: {
                        top: 100,
                        right: 10
                    },
                    bgcolor: '#0096df',
                    click: function (type) {
                        const clickEle = this;

                        const okexSpotCacheConfig = CacheHelper.get(okexSpotConfigCacheKey);
                        Object.assign(okexSpotConfig, okexSpotCacheConfig);
                        if (type === "bar1") {
                            //页面层
                            const formHtml = GM_getResourceText('frm-okex-spot-setting');
                            const settingLayerIndex = layer.open({
                                title: '配置',
                                type: 1,
                                skin: 'layui-layer-rim', //加上边框
                                area: ['800px', '540px'], //宽高
                                content: formHtml
                            });
                            form.render();
                            //默认值
                            //formTest 即 class="layui-form" 所在元素对应的 lay-filter="" 对应的值

                            const frmFitter = 'okex-setting';
                            form.val(frmFitter, okexSpotConfig);
                            //进度条滑动
                            element.progress('finishRate', okexSpotConfig.finishRate + '%');
                            progressSlider.render('finishRate', (percent) => {
                                form.val(frmFitter, {
                                    finishRate: percent
                                });
                            });
                            //工作时间范围
                            laydate.render({
                                elem: '.jobTimeRange',
                                type: 'time',
                                range: true,
                                format: 'HH:mm'
                            });

                            //监听提交
                            form.on('submit(frm-okex-save)', function (data) {
                                Object.assign(okexSpotConfig, data.field);
                                CacheHelper.set(okexSpotConfigCacheKey, okexSpotConfig);
                                layer.close(settingLayerIndex);
                                layer.msg('保存成功');
                                return false;
                            });

                        } else if (type === 'bar2') {
                            const bar2Self = this;

                            if (unsafeWindow.OK_GLOBAL && OK_GLOBAL.ws && !OK_GLOBAL.ws.isInjected) {
                                layer.alert('未替换对应脚本，请先在扩展reRes替换对应脚本websocket.js', { icon: 5 });
                                return;
                            }
                            $(bar2Self).text('');
                            if (okexSpotConfig.isEnabled) {
                                $(bar2Self).removeClass('layui-icon-pause').addClass('layui-icon-play');
                                self.stopTrade();
                            } else {
                                $(bar2Self).addClass('layui-icon-pause').removeClass('layui-icon-play');
                                self.startTrade();
                            }
                        }
                    }
                });
            }
        });
    }

    setOkexEntrustTime(time) {
        OkexC2CWebUtils.taskRun(() => {
            //模块设置
            unsafeWindow.webpackJsonp && webpackJsonp([1], [function (e, t, n) {
                for (const key in n.c) {
                    if (n.c.hasOwnProperty(key)) {
                        const esModule = n.c[key];
                        //请求时间配置
                        if (esModule.exports && esModule.exports.default && esModule.exports.default.entrustTime) {
                            const timeConfig = esModule.exports.default;
                            timeConfig.entrustTime = time;
                            break;
                        }
                    }
                }
            }]);
        });
    }

    startTrade() {
        const self = this;
        const layer = layui.layer;

        if (tradeType.isC2C) {//c2c
            Object.assign(okexC2CConfig, {
                isEnabled: true
            });
            CacheHelper.set(okexC2CConfigCacheKey, okexC2CConfig);

            const logMsg = `开启C2C自动交易`;
            layer.msg(logMsg);
            OkexC2CWebUtils.log(logMsg);
            const c2cTradeHelper = new C2CTradeHelper(okexC2CConfig);
            c2cTradeHelper.autoOrderTrade();
            self.setOkexEntrustTime(okexC2CConfig.entrustTime);
        }
        else if (tradeType.isSpot) {//spot
            Object.assign(okexSpotConfig, {
                isEnabled: true
            });
            CacheHelper.set(okexSpotConfigCacheKey, okexSpotConfig);

            const logMsg = `开启币币自动交易`;
            layer.msg(logMsg);
            OkexSpotWebUtils.log(logMsg);
            const spotTradeHelper = new SpotTradeHelper(okexSpotConfig);
            unsafeWindow.calcDepth = spotTradeHelper.calcDepth.bind(spotTradeHelper);

        } else {
            layer.msg(`非匹配URL`);
        }
    }

    stopTrade() {
        const self = this;
        const layer = layui.layer;

        if (tradeType.isC2C) {//c2c
            Object.assign(okexC2CConfig, {
                isEnabled: false
            });
            CacheHelper.set(okexC2CConfigCacheKey, okexC2CConfig);

            const logMsg = `停止C2C自动交易`;
            layer.msg(logMsg);
            OkexC2CWebUtils.log(logMsg);
            location.reload();
        } else if (tradeType.isSpot) {//spot
            const okexSpotCacheConfig = CacheHelper.get(okexSpotConfigCacheKey);
            Object.assign(okexSpotConfig, okexSpotCacheConfig, {
                isEnabled: false
            });
            CacheHelper.set(okexSpotConfigCacheKey, okexSpotConfig);

            const logMsg = `停止币币自动交易`;
            layer.msg(logMsg);
            OkexSpotWebUtils.log(logMsg);
            location.reload();
        } else {
            layer.msg(`非匹配URL`);
        }
    }
}

unsafeWindow.GmUserJs = new GmUserJs();